package com.rcloud.stock.ui.search;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.rcloud.stock.bean.Stock;
import com.rcloud.stock.database.History;
import com.rcloud.stock.database.Repository;
import com.rcloud.stock.net.ServerAddress;
import com.rcloud.stock.net.VolleySingleton;

import java.util.Arrays;
import java.util.List;

import static android.content.ContentValues.TAG;

public class SearchViewModel extends AndroidViewModel {
    private final Repository repository;
    private final MutableLiveData<List<Stock>> stocks = new MutableLiveData<>();
    private final MutableLiveData<String> patternLive = new MutableLiveData<>();
    public MutableLiveData<String> getPatternLive(){return patternLive;}
    public LiveData<List<History>> getHistories() {
        return repository.getHistories();
    }

    public MutableLiveData<List<Stock>> getStocks(){
        return stocks;
    }

    public SearchViewModel(@NonNull Application application) {
        super(application);
        repository = new Repository(application);
    }

    public void insertHistory(History history){
        repository.insertHistories(history);
    }

    public void deleteHistory(History history){
        repository.deleteHistories(history);
    }

    public void fetchStockWithPattern(String pattern){
        StringRequest request = new StringRequest(Request.Method.GET,
                ServerAddress.ROOT+"search_stock?pattern="+pattern,
                response -> {
                    Gson gson = new Gson();
                    Stock[] stocks = gson.fromJson(response,Stock[].class);
                    this.stocks.setValue(Arrays.asList(stocks));
                },error -> {
            Log.d(TAG, "fetchStockWithPattern: 请求失败");
        });
        request.setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        VolleySingleton.getInstance(getApplication()).getRequestQueue().add(request);
    }
}
